package com.cuotigou.service.impl;

import com.cuotigou.config.ConfigUtils;
import com.cuotigou.mapper.*;
import com.cuotigou.pojo.*;
import com.cuotigou.service.WrongTopicService;
import com.cuotigou.util.wordUtil;
import com.cuotigou.util.*;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * Created by Administrator on 2018/11/1.
 */
@Service
@Transactional
public class WrongTopicServiceImpl implements WrongTopicService {


    private static final Logger log = LoggerFactory.getLogger(WrongTopicServiceImpl.class);

    @Autowired
    private SSubjectMapper sSubjectMapper;
    @Autowired
    private SWrongTopicMapper sWrongTopicMapper;
    @Autowired
    private SUserMapper sUserMapper;
    @Autowired
    private SWrongTopicLabelMapper sWrongTopicLabelMapper;
    @Autowired
    private SUserToWrongTopicMapper sUserToWrongTopicMapper;
    @Autowired
    private SLabelMapper sLabelMapper;
    @Autowired
    private SConfigMapper sConfigMapper;
    @Autowired
    private SKeywordMapper sKeywordMapper;
    @Autowired
    private SWrongTopicKeywordMapper sWrongTopicKeywordMapper;

    @Override
    public ObjectResult index(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());
        SUser sUser = sUserMapper.selectByPrimaryKey(Long.parseLong(userId));

        List<SSubject> list = sSubjectMapper.selectSubjectListByGradeId(sUser.getGradeId());
        for (SSubject sSubject:list){
            Map<String,Object> map = new HashMap<>();
            map.put("userId",userId);
            map.put("subjectId",sSubject.getId());
            map.put("isDelete",0);
            List<SWrongTopic> sWrongTopics = sWrongTopicMapper.selectWrongTopicByMap(map);
            sSubject.setCount(sWrongTopics.size());
            sSubject.setImage(ConfigUtils.ADMIN_URL+sSubject.getImage());
        }
        return ObjectResult.build("1","成功",list);
    }

    @Override
    public ObjectResult subjectWrongTopicDetails(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());

        Map<String,Object> map = new HashMap<>();
        Map<String,Object> data = new HashMap<>();
        map.put("userId",userId);
        map.put("subjectId",xmlBean.getId());
        map.put("isPrinter",xmlBean.getIsPrinter());

        if(!StringUtil.isEmpty(xmlBean.getSubject())){
            if("全部".equals(xmlBean.getSubject())){
                map.put("subject",null);
            }else {
                map.put("subject",xmlBean.getSubject());
            }
        }

        //type 0 已收集 1 已掌握 2 已删除
        if("0".equals(xmlBean.getType())){
            map.put("status","(0,1)");
        }
        if("1".equals(xmlBean.getType())){
            map.put("status","(2)");
        }
        if("2".equals(xmlBean.getType())){
            map.put("isDelete",1);
            map.put("status",null);
        }else {
            map.put("isDelete",0);
        }

        if (StringUtil.isEmpty(xmlBean.getTitle())){
            map.put("title",null);
        }else {
            map.put("title","%"+xmlBean.getTitle()+"%");
        }

        if(!StringUtil.isEmpty(xmlBean.getIsPrinter())){
            map.put("isDelete",null);
        }

        List<SWrongTopic> sWrongTopics = new ArrayList<>();
        if (!StringUtil.isEmpty(xmlBean.getIsHot())){
            map.put("isHot",xmlBean.getIsHot());
            sWrongTopics= sWrongTopicMapper.selectWrongTopicIsHot(map);
        }else {
            sWrongTopics = sWrongTopicMapper.selectWrongTopicByMap(map);
        }

        //分页
        Page<SWrongTopic> page = new Page<>();
        page.setP(xmlBean.getP()==null? 1:Integer.parseInt(xmlBean.getP()));
        List<SWrongTopic> content = page.getPageContent(sWrongTopics);

        //返回图片数组
        for (SWrongTopic sWrongTopic:content){
            if(sWrongTopic.getType()==1){
                sWrongTopic.setStemArray(sWrongTopic.getStem().split(","));
//                sWrongTopic.setOriginalArray(sWrongTopic.getOriginal().split(","));
//                sWrongTopic.setAnswerArray(sWrongTopic.getAnswer().split(","));
            }else {
                String[] array ={"http://app.scjapp.com:8088/image/offereward/1546420379066.jpg"};
                sWrongTopic.setStemArray(array);
                sWrongTopic.setStem(StringEscapeUtils.unescapeHtml4(sWrongTopic.getStem()));
                sWrongTopic.setAnswer(StringEscapeUtils.unescapeHtml4(sWrongTopic.getAnswer()));
            }

            sWrongTopic.setLabelList(sWrongTopicLabelMapper.select(sWrongTopic.getId()));

        }

        if(!StringUtil.isEmpty(xmlBean.getType())){
            map.put("status",null);
            map.put("isDelete",1);
            Integer count3 = sWrongTopicMapper.selectWrongTopicCountByMap(map);
            map.put("isDelete",0);
            map.put("status","(0,1)");
            Integer  count1 = sWrongTopicMapper.selectWrongTopicCountByMap(map);
            map.put("status","(2)");
            Integer count2 = sWrongTopicMapper.selectWrongTopicCountByMap(map);
            Integer[]  array = {count1,count2,count3};
            data.put("array",array);
        }

        data.put("list",content);
        data.put("count",page.getPageTotal());

        return ObjectResult.build("1","成功",data);
    }

    @Override
    public ObjectResult wrongTopicupload(XMLBean xmlBean, MultipartFile[] stemFiles,MultipartFile[] answerFiles,MultipartFile[] originalFiles) {
        try {
            String userId = CommonUtils.decToken(xmlBean.getToken());
            String sentence = "";

            if (StringUtil.isEmpty(xmlBean.getLabel())) return ObjectResult.build("0","标签不能为空");
            if (StringUtil.isEmpty(xmlBean.getSubject())) return ObjectResult.build("0","请选择科目");

            SUser sUser = sUserMapper.selectByPrimaryKey(Long.parseLong(userId));
            String not_vip = sConfigMapper.select("not_vip");
            Integer count = sUserToWrongTopicMapper.selctCount(Long.parseLong(userId));
            if(count >= Integer.parseInt(not_vip) &&  sUser.getExpireTime().compareTo(new Date())<0){
                return ObjectResult.build("1","非会员最多可导入管理"+not_vip+"道错题",0);
            }

            //科目id
            Map<String,Object> map = new HashMap<>();
            map.put("gradeId",sUser.getGradeId());
            map.put("labelId",xmlBean.getSubject());
            Integer subjectId = sSubjectMapper.selectSubjectId(map);

            if (subjectId==null){
                return ObjectResult.build("0","科目错误");
            }

            SWrongTopic sWrongTopic = new SWrongTopic();
            //拍题上传
            if (xmlBean.getType().equals("1")){
                if (originalFiles.length<1) return ObjectResult.build("0","原图不能为空");

                sWrongTopic.setUserId(Long.parseLong(userId));
                sWrongTopic.setSubjectId(subjectId);
                sWrongTopic.setAddTime(new Date());
                sWrongTopic.setRemark(xmlBean.getRemark().trim());
                sWrongTopic.setType(Integer.parseInt(xmlBean.getType()));
                sWrongTopic.setGradeId(sUser.getGradeId());

                //题干
                StringBuilder stemBuilder = new StringBuilder();
                List<String> stemList = FileUtil.upload(stemFiles, ConfigUtils.STEM_URL);

                int i = 1;
                for (String stem:stemList){
                    if(i==stemList.size()){
                        stemBuilder.append(ConfigUtils.FILE_URL+"image/stem/"+stem);
                    }else {
                        stemBuilder.append(ConfigUtils.FILE_URL+"image/stem/"+stem+",");
                    }
                    i++;
                }

                sWrongTopic.setStem(stemBuilder.toString());

                //原图
                StringBuilder originalBuilder = new StringBuilder();
                List<String> originalList = FileUtil.upload(originalFiles, ConfigUtils.ORIGINAL_URL);
                i = 1;
                for (String original:originalList){
                    if(i==originalList.size()) {
                        originalBuilder.append(ConfigUtils.FILE_URL + "image/original/" + original);
                    }else {
                        originalBuilder.append(ConfigUtils.FILE_URL + "image/original/" + original + ",");
                    }
                    i++;
                }

                sWrongTopic.setOriginal(originalBuilder.toString());

                //正解
                if (answerFiles.length>0) {
                    StringBuilder answerBuilder = new StringBuilder();
                    List<String> answerlList = FileUtil.upload(answerFiles, ConfigUtils.ANSWER_URL);
                    i = 1;
                    for (String answer:answerlList){
                        if(i==answerlList.size()) {
                            answerBuilder.append(ConfigUtils.FILE_URL + "image/answer/" + answer);
                        }else {
                            answerBuilder.append(ConfigUtils.FILE_URL + "image/answer/" + answer + ",");
                        }
                    }
                    sWrongTopic.setAnswer(answerBuilder.toString());
                }

                //识别图片中的文字
                String[] split = sWrongTopic.getOriginal().split(",");
                StringBuilder builder = new StringBuilder();

                for (int j = 0;j<split.length;j++){
                    String replaceAll = split[j].replaceAll(ConfigUtils.FILE_URL, "C:/tomcat8088/webapps/");
                    log.info("replaceAll:"+replaceAll);
                    String str = OcrUtil.generalRecognition(replaceAll);
                    builder.append(str);
                }
                sentence = builder.toString();
                sWrongTopic.setDistinguish(sentence);

            }
//        文字录入
            if(xmlBean.getType().equals("2")) {
                if (StringUtil.isEmpty(xmlBean.getStem())) return ObjectResult.build("0","题干不能为空");

                sWrongTopic.setUserId(Long.parseLong(userId));
                sWrongTopic.setSubjectId(subjectId);
                sWrongTopic.setStem(xmlBean.getStem());
                sWrongTopic.setAnswer(xmlBean.getAnswer());
                sWrongTopic.setRemark(xmlBean.getRemark());
                sWrongTopic.setAddTime(new Date());
                sWrongTopic.setGradeId(sUser.getGradeId());
                sWrongTopic.setType(Integer.parseInt(xmlBean.getType()));

                sentence = sWrongTopic.getStem();
            }

            sWrongTopicMapper.insertSelective(sWrongTopic);

            //错题关键字中间表
            List<String> analysis = SolrUtil.getAnalysis(sentence);
            if(analysis.size()>0) {

                List<Integer> list = sKeywordMapper.selctKeyword(analysis);
                if(sentence.contains("+")){
                    list.add(5);
                }
                if(sentence.contains("-")){
                    list.add(6);
                }
                if(sentence.contains("÷")){
                    list.add(7);
                }
                if(sentence.contains("×")){
                    list.add(8);
                }
                if(sentence.contains("*")){
                    list.add(9);
                }
                if(list.size()>0) {
                    for (Integer i : list) {
                        SWrongTopicKeyword sWrongTopicKeyword = new SWrongTopicKeyword();
                        sWrongTopicKeyword.setTopicId(sWrongTopic.getId());
                        sWrongTopicKeyword.setKeywordId(i);
                        sWrongTopicKeywordMapper.insertSelective(sWrongTopicKeyword);
                    }
                }
            }

            //错题标签中间表
            String[] labels = xmlBean.getLabel().split(",");
            for (int i =0;i<labels.length;i++){
                if(!StringUtil.isEmpty(labels[i])) {
                    SWrongTopicLabel sWrongTopicLabel = new SWrongTopicLabel();
                    sWrongTopicLabel.setLabelId(Integer.parseInt(labels[i]));
                    sWrongTopicLabel.setTopicId(sWrongTopic.getId());
                    sWrongTopicLabelMapper.insert(sWrongTopicLabel);
                }
            }

            //掌握程度
            Integer status = 0;
            String title = sLabelMapper.selectByPrimaryKey(Long.parseLong(xmlBean.getStatus())).getTitle();
            switch (title){
                case "不懂"  :  status = 0;break;
                case "基本懂":  status = 1;break;
                case "完全懂":  status = 2;break;
                default:break;
            }

            //用户错题表
            SUserToWrongTopic sUserToWrongTopic = new SUserToWrongTopic();
            sUserToWrongTopic.setUserId(Long.parseLong(userId));
            sUserToWrongTopic.setTopicId(sWrongTopic.getId());
            sUserToWrongTopic.setIsPrinter(0);
            sUserToWrongTopic.setIsDelete(0);
            sUserToWrongTopic.setStatus(status);
            sUserToWrongTopic.setAddTime(new Date());
            sUserToWrongTopic.setModify(new Date());
            sUserToWrongTopicMapper.insertSelective(sUserToWrongTopic);

        }catch (RuntimeException e){
            ExceptionUtil.logError(e,log);
            return ObjectResult.build("0","录题失败,请联系客服");
        }
        return ObjectResult.build("1","录题成功",1);

    }

    @Override
    public ObjectResult wrongTopicupDelete(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());

        try {
            String[] split = null;
            if(xmlBean.getId().contains(",")){
                split = xmlBean.getId().split(",");
            }else {
                String [] s = {xmlBean.getId()};
                split = s;
            }

            for (int i =0;i<split.length;i++) {

                SWrongTopic sWrongTopic1 = sWrongTopicMapper.selectByPrimaryKey(Long.parseLong(split[i]));

                if (Long.parseLong(userId) == sWrongTopic1.getUserId()) {
                    SWrongTopic sWrongTopic = new SWrongTopic();
                    sWrongTopic.setId(Long.parseLong(split[i]));
                    sWrongTopic.setIsDelete(sWrongTopic1.getIsDelete() == 0 ? 1 : 0);
                    sWrongTopicMapper.updateByPrimaryKeySelective(sWrongTopic);
                }

                SUserToWrongTopic sUserToWrongTopic = new SUserToWrongTopic();
                sUserToWrongTopic.setTopicId(Long.parseLong(split[i]));
                sUserToWrongTopic.setUserId(Long.parseLong(userId));
                SUserToWrongTopic select = sUserToWrongTopicMapper.select(sUserToWrongTopic);
                if (select != null) {
                    sUserToWrongTopic.setIsDelete(select.getIsDelete()== 0 ? 1:0);
                    sUserToWrongTopicMapper.update(sUserToWrongTopic);
                }
            }
        }catch (RuntimeException e){
            ExceptionUtil.logError(e,log);
            return ObjectResult.build("0","操作失败");
        }

        return ObjectResult.build("1","操作成功");
    }

    @Override
    public ObjectResult wrongTopicupRealDelete(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());

        SUserToWrongTopic sUserToWrongTopic = new SUserToWrongTopic();
        sUserToWrongTopic.setUserId(Long.parseLong(userId));
        sUserToWrongTopic.setTopicId(Long.parseLong(xmlBean.getId()));
        sUserToWrongTopicMapper.delete(sUserToWrongTopic);
        return ObjectResult.build("1","成功");
    }

    @Override
    public ObjectResult wrongTopicupUpdate(XMLBean xmlBean) {

        try {
            SUserToWrongTopic sUserToWrongTopic = new SUserToWrongTopic();
            sUserToWrongTopic.setStatus(Integer.parseInt(xmlBean.getStatus()));
            if(xmlBean.getId().contains(",")){
                sUserToWrongTopic.setArray(xmlBean.getId().split(","));
            }else {
                String [] s = {xmlBean.getId()};
                sUserToWrongTopic.setArray(s);
            }
            sUserToWrongTopicMapper.update(sUserToWrongTopic);
        }catch (RuntimeException e){
            ExceptionUtil.logError(e,log);
            return ObjectResult.build("0","修改错题状态失败");
        }

        return ObjectResult.build("1","修改错题状态成功");
    }

    @Override
    public ObjectResult wrongTopicupEdit(XMLBean xmlBean,MultipartFile[] stemFiles, MultipartFile[] answerFiles, MultipartFile[] originalFiles) {
        try {
            String userId = CommonUtils.decToken(xmlBean.getToken());

            SUser sUser = sUserMapper.selectByPrimaryKey(Long.parseLong(userId));

            if (StringUtil.isEmpty(xmlBean.getLabel())) return ObjectResult.build("0","标签不能为空");

            SWrongTopic sWrongTopic = sWrongTopicMapper.selectByPrimaryKey(Long.parseLong(xmlBean.getId()));
            if(sWrongTopic == null) return ObjectResult.build("0","找不到该错题");
            if(!userId.equals(sWrongTopic.getUserId().toString())) return ObjectResult.build("0","非错题上传者");

            //科目id
            Map<String,Object> map = new HashMap<>();
            map.put("gradeId",sUser.getGradeId());
            map.put("labelId",xmlBean.getSubject());
            Integer subjectId = sSubjectMapper.selectSubjectId(map);

            if (subjectId==null){
                return ObjectResult.build("0","科目错误");
            }

            //拍题上传
            if (sWrongTopic.getType()==1){
                sWrongTopic.setModifyTime(new Date());
                sWrongTopic.setRemark(xmlBean.getRemark().trim());
                sWrongTopic.setSubjectId(subjectId);

                //题干
                if(stemFiles.length>0) {
                    StringBuilder stemBuilder = new StringBuilder();
                    List<String> stemList = FileUtil.upload(stemFiles, ConfigUtils.STEM_URL);

                    int i = 1;
                    for (String stem : stemList) {
                        if (i == stemList.size()) {
                            stemBuilder.append(ConfigUtils.FILE_URL + "image/stem/" + stem);
                        } else {
                            stemBuilder.append(ConfigUtils.FILE_URL + "image/stem/" + stem + ",");
                        }
                        i++;
                    }

                    sWrongTopic.setStem(stemBuilder.toString());
                }

                //原图
                if(originalFiles.length>0) {
                    StringBuilder originalBuilder = new StringBuilder();
                    List<String> originalList = FileUtil.upload(originalFiles, ConfigUtils.ORIGINAL_URL);
                    int  i = 1;
                    for (String original : originalList) {
                        if (i == originalList.size()) {
                            originalBuilder.append(ConfigUtils.FILE_URL + "image/original/" + original);
                        } else {
                            originalBuilder.append(ConfigUtils.FILE_URL + "image/original/" + original + ",");
                        }
                        i++;
                    }

                    sWrongTopic.setOriginal(originalBuilder.toString());
                }

                //正解
                if(answerFiles.length>0) {
                    StringBuilder answerBuilder = new StringBuilder();
                    List<String> answerlList = FileUtil.upload(answerFiles, ConfigUtils.ANSWER_URL);
                    int i = 1;
                    for (String answer : answerlList) {
                        if (i == answerlList.size()) {
                            answerBuilder.append(ConfigUtils.FILE_URL + "image/answer/" + answer);
                        } else {
                            answerBuilder.append(ConfigUtils.FILE_URL + "image/answer/" + answer + ",");
                        }
                    }
                    sWrongTopic.setAnswer(answerBuilder.toString());
                }

            }

//        文字录入
            if(sWrongTopic.getType()==2) {
                sWrongTopic.setStem(xmlBean.getStem());
                sWrongTopic.setAnswer(xmlBean.getAnswer());
                sWrongTopic.setSubjectId(subjectId);
                sWrongTopic.setRemark(xmlBean.getRemark());
                sWrongTopic.setModifyTime(new Date());
            }

            //修改错题
            sWrongTopicMapper.updateByPrimaryKeySelective(sWrongTopic);

            //删错所有错题标签后，再添加错题标签表
            sWrongTopicLabelMapper.delete(sWrongTopic.getId());
            String[] labels = xmlBean.getLabel().split(",");
            for (int i =0;i<labels.length;i++){
                if(!StringUtil.isEmpty(labels[i])) {
                    SWrongTopicLabel sWrongTopicLabel = new SWrongTopicLabel();
                    sWrongTopicLabel.setLabelId(Integer.parseInt(labels[i]));
                    sWrongTopicLabel.setTopicId(sWrongTopic.getId());
                    sWrongTopicLabelMapper.insert(sWrongTopicLabel);
                }
            }

            //掌握程度
            Integer status = 0;
            String title = sLabelMapper.selectByPrimaryKey(Long.parseLong(xmlBean.getStatus())).getTitle();
            switch (title){
                case "不懂"  :  status = 0;break;
                case "基本懂":  status = 1;break;
                case "完全懂":  status = 2;break;
                default:break;
            }

            //修改用户错题表
            SUserToWrongTopic sUserToWrongTopic = new SUserToWrongTopic();
            sUserToWrongTopic.setUserId(Long.parseLong(userId));
            sUserToWrongTopic.setTopicId(sWrongTopic.getId());
            sUserToWrongTopic.setStatus(status);
            sUserToWrongTopicMapper.update(sUserToWrongTopic);

        }catch (RuntimeException e){
            ExceptionUtil.logError(e,log);
            return ObjectResult.build("0","修改失败,请联系客服");
        }
        return ObjectResult.build("1","修改成功");
    }


    @Override
    public ObjectResult subject(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());
        List<SSubject> list = sSubjectMapper.selectSubjectListByGradeId(sUserMapper.selectByPrimaryKey(Long.parseLong(userId)).getGradeId());
        return ObjectResult.build("1","成功",list);
    }

    @Override
    public ObjectResult wrongTopicHot(XMLBean xmlBean) {

        List<SWrongTopic> sWrongTopics = sWrongTopicMapper.selectWrongTopicHot(Long.parseLong(xmlBean.getId()));
        //分页
        Page<SWrongTopic> page = new Page<>();
        page.setP(xmlBean.getP()==null? 0:Integer.parseInt(xmlBean.getP()));
        List<SWrongTopic> list = page.getPageContent(sWrongTopics);

        Map<String,Object> map = new HashMap<>();
        map.put("list",list);
        map.put("counr",page.getPageTotal());
        return ObjectResult.build("1","成功",map);
    }

    @Override
    public ObjectResult review(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());
        SUser sUser = sUserMapper.selectByPrimaryKey(Long.parseLong(userId));

        if(sUser.getExpireTime().compareTo(new Date())<0){
            sUser.setIsVip(0);
            sUserMapper.updateByPrimaryKeySelective(sUser);
            return ObjectResult.build("0","非会员无法使用题库复习");
        }

        Map<String,Object> map = new HashMap<>();
        if(!StringUtil.isEmpty(xmlBean.getLabel())) {
            String[] split = xmlBean.getLabel().split(",");
            map.put("array", split);
            map.put("count", split.length);
        }
        map.put("subjectId",xmlBean.getId());
        switch (xmlBean.getCountId()){
            case "39":
                map.put("sql","count = 0");break;
            case "40":
                map.put("sql","count = 1");break;
            case "41":
                map.put("sql","count = 2");break;
            case "42":
                map.put("sql","count &gt;=3");break;
            default:break;
        }
        switch (xmlBean.getLevelId()){
            case "43":
                map.put("level","(0,1,2)");break;
            case "44":
                map.put("level","(3)");break;
            case "45":
                map.put("level","(4,5)");break;
            default:break;
        }
        List<SWrongTopic> list = sWrongTopicMapper.selectReviewByMap(map);

        Page<SWrongTopic> page = new Page<>();
        page.setP(xmlBean.getP()==null? 1:Integer.parseInt(xmlBean.getP()));
        List<SWrongTopic> content = page.getPageContent(list);
        for (SWrongTopic sWrongTopic:content){
            if(sWrongTopic.getType()==1){
                sWrongTopic.setStemArray(sWrongTopic.getStem().split(","));
//                sWrongTopic.setOriginalArray(sWrongTopic.getOriginal().split(","));
//                sWrongTopic.setAnswerArray(sWrongTopic.getAnswer().split(","));
            }else if (!StringUtil.isEmpty(sWrongTopic.getStem())){
                sWrongTopic.setStem(StringEscapeUtils.unescapeHtml4(sWrongTopic.getStem()));
            }
            sWrongTopic.setLabelList(sWrongTopicLabelMapper.select(sWrongTopic.getId()));
            if (!StringUtil.isEmpty(sWrongTopic.getAnswer())){
                sWrongTopic.setAnswer(StringEscapeUtils.unescapeHtml4(sWrongTopic.getAnswer()));
            }
        }

        map.clear();
        map.put("list",content);
        map.put("count",page.getPageTotal());
        return ObjectResult.build("1","成功",map);
    }

    @Override
    public ObjectResult wrongTopicScreen(XMLBean xmlBean) {
        try {
            String userId = CommonUtils.decToken(xmlBean.getToken());
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> data = new HashMap<>();
            StringBuilder builder = new StringBuilder();

            map.put("userId", userId);
            map.put("subjectId", xmlBean.getId());
            map.put("isDelete",0);
            //导入时间
            if ("78".equals(xmlBean.getTimeId())){
                map.put("addTime", DateUtil.addDateDay(new Date(), -7));
            }
            if ("79".equals(xmlBean.getTimeId())){
                map.put("addTime", DateUtil.addDateDay(new Date(), -30));
            }

            //打印次数
            switch (xmlBean.getCountId()) {
                case "39":
                    map.put("sql", "swt.count = 0");
                    break;
                case "40":
                    map.put("sql", "swt.count = 1");
                    break;
                case "41":
                    map.put("sql", "swt.count = 2");
                    break;
                case "42":
                    map.put("sql", "swt.count >= 3");
                    break;
                default:
                    break;
            }
            //知识点
            if (!"0".equals(xmlBean.getKnowledgeId())) {
                builder.append(xmlBean.getKnowledgeId()).append(",");
            }
            //错题原因
            if (!"0".equals(xmlBean.getReasonId())) {
                builder.append(xmlBean.getReasonId()).append(",");
            }
            //题型
            if (!"0".equals(xmlBean.getQuestiontypeId())) {
                builder.append(xmlBean.getQuestiontypeId()).append(",");
            }

            //错题来源
            if (!"0".equals(xmlBean.getSourceId())) {
                builder.append(xmlBean.getSourceId());
            }

            //type 0 已收集 1 已掌握 2 已删除
            if("0".equals(xmlBean.getType())){
                map.put("status","(0,1)");
            }
            if("1".equals(xmlBean.getType())){
                map.put("status","(2)");
            }
            if("2".equals(xmlBean.getType())){
                map.put("isDelete",1);
                map.put("status",null);
            }

            //去除最后的逗号
            String str = builder.toString();
            if(!StringUtil.isEmpty(str)) {
                if(str.contains(",")){
                    String substring = str.substring(str.lastIndexOf(","));
                    if (substring.equals(",")) {
                        str = str.substring(0, str.lastIndexOf(","));
                    }
                    String[] split = str.split(",");
                    map.put("array", split);
                    map.put("count",split.length);
                }else {
                    String[] array = {builder.toString()};
                    map.put("array", array);
                    map.put("count",1);
                }
            }

            List<SWrongTopic> list = sWrongTopicMapper.selectScreenByMap(map);

            Page<SWrongTopic> page = new Page<>();
            page.setP(xmlBean.getP() == null ? 1 : Integer.parseInt(xmlBean.getP()));
            List<SWrongTopic> content = page.getPageContent(list);
            for (SWrongTopic sWrongTopic : content) {
                if (sWrongTopic.getType() == 1) {
                    sWrongTopic.setStemArray(sWrongTopic.getStem().split(","));
//                sWrongTopic.setOriginalArray(sWrongTopic.getOriginal().split(","));
//                sWrongTopic.setAnswerArray(sWrongTopic.getAnswer().split(","));
                }else {
                    String[] array ={"http://app.scjapp.com:8088/image/offereward/1546420379066.jpg"};
                    sWrongTopic.setStemArray(array);
                    sWrongTopic.setStem(StringEscapeUtils.unescapeHtml4(sWrongTopic.getStem()));
                }
                sWrongTopic.setLabelList(sWrongTopicLabelMapper.select(sWrongTopic.getId()));
            }

            if(!StringUtil.isEmpty(xmlBean.getType())){
                map.put("isDelete",1);
                Integer count3 = sWrongTopicMapper.selectScreenByMap(map).size();
                map.put("isDelete",0);
                map.put("status","(0,1)");
                Integer  count1 = sWrongTopicMapper.selectScreenByMap(map).size();
                map.put("status","(2)");
                Integer count2 = sWrongTopicMapper.selectScreenByMap(map).size();
                Integer[]  array = {count1,count2,count3};
                data.put("array",array);
            }

            data.put("list", content);
            data.put("count", page.getPageTotal());
            return ObjectResult.build("1", "成功", data);
        }catch (RuntimeException e){
            ExceptionUtil.logError(e,log);
            return ObjectResult.build("0","筛选失败");
        }
    }

    @Override
    public ObjectResult wrongTopicDetails(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());

        SWrongTopic sWrongTopic = sWrongTopicMapper.selectByPrimaryKey(Long.parseLong(xmlBean.getId()));
        if (sWrongTopic==null){
            return   ObjectResult.build("0","不存在的错题");
        }

        SUserToWrongTopic sUserToWrongTopic = new SUserToWrongTopic();
        sUserToWrongTopic.setUserId(Long.parseLong(userId));
        sUserToWrongTopic.setTopicId(Long.parseLong(xmlBean.getId()));
        sUserToWrongTopic.setIsDelete(0);
        SUserToWrongTopic select = sUserToWrongTopicMapper.select(sUserToWrongTopic);
        if (select == null ){
            sWrongTopic.setIs_join(0);
        }else if (select.getIsDelete()==0){
            sWrongTopic.setIs_join(0);
        }else {
            sWrongTopic.setIs_join(0);
        }

        if (sWrongTopic.getType()==1){
            if(!StringUtil.isEmpty(sWrongTopic.getStem())) {
                sWrongTopic.setStemArray(sWrongTopic.getStem().split(","));
            }else {
                String[] s =  {};
                sWrongTopic.setStemArray(s);
            }
            if(!StringUtil.isEmpty(sWrongTopic.getAnswer()) ){
                sWrongTopic.setAnswerArray(sWrongTopic.getAnswer().split(","));
            }else {
                String[] s =  {};
                sWrongTopic.setAnswerArray(s);
            }

            if(!StringUtil.isEmpty(sWrongTopic.getOriginal())){
                sWrongTopic.setOriginalArray(sWrongTopic.getOriginal().split(","));
            }else {
                String[] s =  {};
                sWrongTopic.setOriginalArray(s);
            }
        }else {
//            sWrongTopic.setStem(StringUtil.getTextFromTHML(StringEscapeUtils.unescapeHtml4(sWrongTopic.getStem())));
        }

        if (sWrongTopic.getAnswer()==null){
            sWrongTopic.setAnswer("");
        }else {
//            sWrongTopic.setAnswer(StringUtil.getTextFromTHML(StringEscapeUtils.unescapeHtml4(sWrongTopic.getAnswer())));
        }

        sWrongTopic.setIdList(sWrongTopicLabelMapper.selectId(sWrongTopic.getId()));
        SSubject sSubject = sSubjectMapper.selectByPrimaryKey(sWrongTopic.getSubjectId());
        sWrongTopic.setTitle(sSubject.getTitle());

        return ObjectResult.build("1","成功",sWrongTopic);
    }

    @Override
    public ObjectResult learnByAnalogy(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());

        SUser sUser = sUserMapper.selectByPrimaryKey(Long.parseLong(userId));

        if(sUser.getExpireTime().compareTo(new Date())<0){
            return ObjectResult.build("0","非会员无法使用此功能");
        }

//        List<Integer> integerList = sWrongTopicLabelMapper.selectLabelList(Long.parseLong(xmlBean.getId()));
        List<String> integerList = sWrongTopicKeywordMapper.select(xmlBean.getId());

        if(integerList.size()>0){

            Map<String,Object> map = new HashMap<>();
            map.put("list",integerList);
            map.put("percent",integerList.size()*Double.parseDouble(sConfigMapper.select("percent"))/100d);
            map.put("size",integerList.size());
            map.put("limit",Integer.parseInt(sConfigMapper.select("limit")));
            List<SWrongTopic> list = sWrongTopicMapper.selectLearnByAnalogy(map);
            if(list.size()<1){
                return ObjectResult.build("0","未匹配到适合的题目");
            }
            for (SWrongTopic sWrongTopic:list){
                if (sWrongTopic.getType()==1){
                    String[] split = sWrongTopic.getStem().split(",");
                    if(split.length>3){
                        String[] array = {split[0],split[1],split[2]};
                        sWrongTopic.setStemArray(array);
                    }else {
                        sWrongTopic.setStemArray(split);
                    }
                }
                sWrongTopic.setStem(StringEscapeUtils.unescapeHtml4(sWrongTopic.getStem()));
            }
            return ObjectResult.build("1","成功",list);
        }else {
            return ObjectResult.build("0","未匹配到适合的题目");
        }

    }

    @Override
    public ObjectResult wrongTopicAdd(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());

        try {
            SUserToWrongTopic sUserToWrongTopic = new SUserToWrongTopic();
            sUserToWrongTopic.setUserId(Long.parseLong(userId));
            sUserToWrongTopic.setTopicId(Long.parseLong(xmlBean.getId()));
            sUserToWrongTopic.setAddTime(new Date());
            sUserToWrongTopic.setModify(new Date());

            SUserToWrongTopic select = sUserToWrongTopicMapper.select(sUserToWrongTopic);
            if(select!=null){
                return ObjectResult.build("0","该题已加入错题本");
            }

            sUserToWrongTopicMapper.insertSelective(sUserToWrongTopic);
        }catch (RuntimeException e){
            ExceptionUtil.logError(e,log);
            return ObjectResult.build("0","加入错题本是失败");
        }

        return ObjectResult.build("1","加入错题本是成功");
    }

    @Override
    public ObjectResult wrongTopicPrinter(XMLBean xmlBean) {
        String userId = CommonUtils.decToken(xmlBean.getToken());
        String wordUrl = "";
        List<SWrongTopic> list = new ArrayList<>();
        try {
            if(StringUtil.isEmpty(xmlBean.getId())) return ObjectResult.build("0","请选择要打印的错题");
            String[] split = xmlBean.getId().split(",");
            for (int i = 0;i<split.length;i++){
                SWrongTopic sWrongTopic = sWrongTopicMapper.selectByPrimaryKey(Long.parseLong(split[i]));
                if (sWrongTopic == null) return ObjectResult.build("0","不存在的错题");

                SUserToWrongTopic sUserToWrongTopic = new SUserToWrongTopic();
                sUserToWrongTopic.setUserId(Long.parseLong(userId));
                sUserToWrongTopic.setTopicId(Long.parseLong(split[i]));
//                SUserToWrongTopic select = sUserToWrongTopicMapper.select(sUserToWrongTopic);
//                if (select == null) return ObjectResult.build("0","打印前请先加入错题本");

                list.add(sWrongTopic);
            }

            //打印word
            wordUtil wordUtil = new wordUtil();
            wordUrl = wordUtil.exportPdf("错题打印",list,userId);

            for(SWrongTopic sWrongTopic:list){
                //增加打印次数
                sWrongTopic.setCount(sWrongTopic.getCount()+1);
                sWrongTopicMapper.updateByPrimaryKeySelective(sWrongTopic);

                SUserToWrongTopic sUserToWrongTopic = new SUserToWrongTopic();
                sUserToWrongTopic.setUserId(Long.parseLong(userId));
                sUserToWrongTopic.setTopicId(sWrongTopic.getId());
                sUserToWrongTopic.setIsPrinter(1);

                //已打印
                SUserToWrongTopic select = sUserToWrongTopicMapper.select(sUserToWrongTopic);
                if (select == null) {
                    sUserToWrongTopic.setAddTime(new Date());
                    sUserToWrongTopic.setModify(new Date());
                    sUserToWrongTopic.setIsDelete(2);
                    sUserToWrongTopicMapper.insertSelective(sUserToWrongTopic);
                }else {
                    sUserToWrongTopicMapper.update(sUserToWrongTopic);
                }
            }

        }catch (Exception e){
            ExceptionUtil.logError(e,log);
            return ObjectResult.build("0","打印失败");
        }
        return ObjectResult.build("1","打印成功",wordUrl);
    }

    @Override
    public Map<String,Object> analysie(String userId,String id) {
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> data = new HashMap<>();
        String subjectId = "0".equals(id) ? null:id;

        //用户科目
        LinkedList<SSubject> subject = sSubjectMapper.selectSubjectListByGradeId(sUserMapper.selectByPrimaryKey(Long.parseLong(userId)).getGradeId());
        SSubject sSubject = new SSubject();
        sSubject.setTitle("全部");
        sSubject.setId(0);
        subject.addFirst(sSubject);
        data.put("subject",subject);

        //入题情况
        Map<String,Integer> record = new HashMap<>();
        map.put("userId",userId);
        map.put("subjectId",subjectId);
        map.put("isDelete",0);
        Integer all = sWrongTopicMapper.selectWrongTopicCountByMap(map);

        map.put("status","(2)");
        Integer master = sWrongTopicMapper.selectWrongTopicCountByMap(map);
        List<SUserToWrongTopic> eliminateList2 = new ArrayList<>();
        if(!StringUtil.isEmpty(subjectId)){
            eliminateList2 = sUserToWrongTopicMapper.selectSatusCountByMap2(map);
        }else {
            eliminateList2 = sUserToWrongTopicMapper.selectSatusCountByMap(map);
        }

        map.put("status","(0,1)");
        Integer notMaster = sWrongTopicMapper.selectWrongTopicCountByMap(map);
        List<SUserToWrongTopic> eliminateList1 = new ArrayList<>();
        if(!StringUtil.isEmpty(subjectId)){
            eliminateList1 = sUserToWrongTopicMapper.selectSatusCountByMap2(map);
        }else {
            eliminateList1 = sUserToWrongTopicMapper.selectSatusCountByMap(map);
        }

        record.put("totalCount",all);//全部
        record.put("masterCount",master);//已掌握
        record.put("notMasterCount",notMaster);//未掌握
        data.put("record",record);

        //错题消灭情况
        for (SUserToWrongTopic sUserToWrongTopic1:eliminateList1){
            for (SUserToWrongTopic sUserToWrongTopic2:eliminateList2){
                if(sUserToWrongTopic1.getTitle().equals(sUserToWrongTopic2.getTitle())){
                    sUserToWrongTopic1.setNotMasterCount(sUserToWrongTopic2.getMasterCount());
                    break;
                }
            }
        }

        for (SUserToWrongTopic sUserToWrongTopic2:eliminateList2){
            boolean flag = false;
            for (SUserToWrongTopic sUserToWrongTopic1:eliminateList1){
                if(sUserToWrongTopic1.getTitle().equals(sUserToWrongTopic1.getTitle())){
                    flag = true;
                    break;
                }
            }

            if(!flag){
                eliminateList1.add(sUserToWrongTopic2);
            }
        }

        List<String> title= new ArrayList<>();
        List<Integer> masterCount  = new ArrayList<>();
        List<Integer> notMasterCount  = new ArrayList<>();

        for (SUserToWrongTopic sUserToWrongTopic:eliminateList1){
            if (sUserToWrongTopic.getMasterCount() ==null) sUserToWrongTopic.setMasterCount(0);
            if (sUserToWrongTopic.getNotMasterCount() ==null) sUserToWrongTopic.setNotMasterCount(0);
            title.add(sUserToWrongTopic.getTitle());
            masterCount.add(sUserToWrongTopic.getMasterCount());
            notMasterCount.add(sUserToWrongTopic.getNotMasterCount());

        }

        data.put("title",title);
        data.put("masterCount",masterCount);
        data.put("notMasterCount",notMasterCount);

        //每月录题数量
        List<SUserToWrongTopic> month = sUserToWrongTopicMapper.selectMonthCountByUserId(map);
        Map<String,Integer> months = new LinkedHashMap<>();

        for (SUserToWrongTopic sUserToWrongTopic:month){
            months.put(sUserToWrongTopic.getMonth()+"月",sUserToWrongTopic.getCount());
        }
        data.put("month",months);

        //题型未掌握情况
        LinkedList<SUserToWrongTopic> questionNotMaster = sUserToWrongTopicMapper.selectQuestionNotMasterByUserId(map);
        int total =0;
        for (SUserToWrongTopic sUserToWrongTopic:questionNotMaster){
            total = total+sUserToWrongTopic.getCount();
        }
        SUserToWrongTopic sUserToWrongTopic = new SUserToWrongTopic();

        List<String> questionType = new ArrayList<>();
        List<Integer> questionTypeCount = new ArrayList<>();

        for (SUserToWrongTopic sUserToWrongTopic1:questionNotMaster){
            questionType.add(sUserToWrongTopic1.getTitle());
            questionTypeCount.add(sUserToWrongTopic1.getCount());
        }
        data.put("questionType",questionType);
        data.put("questionTypeCount",questionTypeCount);
        data.put("questionNotMaster",questionNotMaster);

        //科目未掌握情况
        List<SUserToWrongTopic> subjectNotMaster = new ArrayList<>();

        List<String> subjects = new ArrayList<>();
        List<Integer> subjectCount = new ArrayList<>();

        if(subjectId == null){
            subjectNotMaster = sUserToWrongTopicMapper.selectSubjectNotMasterByUserId(userId);
        }else {
            subjectNotMaster = sUserToWrongTopicMapper.selectSatusCountByMap2(map);
            for(SUserToWrongTopic sUserToWrongTopic1:subjectNotMaster){
                sUserToWrongTopic1.setCount(sUserToWrongTopic1.getMasterCount());
                sUserToWrongTopic.setMasterCount(null);
            }
        }

        for(SUserToWrongTopic sUserToWrongTopic1:subjectNotMaster){
            subjects.add(sUserToWrongTopic1.getTitle());
            subjectCount.add(sUserToWrongTopic1.getCount());
        }
        data.put("subjects",subjects);
        data.put("subjectCount",subjectCount);
        data.put("subjectNotMaster",subjectNotMaster);

        //错题原因
        List<SUserToWrongTopic> reason = sUserToWrongTopicMapper.selectReasonByUserId(map);
        Map<String,Integer> reasons = new LinkedHashMap<>();

        for (SUserToWrongTopic userToWrongTopic:reason){;
            reasons.put(userToWrongTopic.getTitle(),userToWrongTopic.getCount());
        }
        data.put("reason",reasons);
        return data;
    }
}
